﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Text;
using CRM.Entity;

using CRM.BLL;
using DP.Web.UI.Controls;
using DP.Web.UI;
using DP.Common;

namespace CRM.Web.ContentAuthorityManage
{
    public partial class Modify : Common.PageBase
    {
        private UserLoginInfo _userLoginInfo;

        /// <summary>
        /// Gets or sets the user ID.
        /// </summary>
        /// <value>
        /// The user ID.
        /// </value>
        public string UserID
        {
            get { return (ViewState["UserID"] == null) ? "" : ViewState["UserID"].ToString(); }
            set { ViewState["UserID"] = value; }
        }

        /// <summary>
        /// Gets or sets the user entity.
        /// </summary>
        /// <value>
        /// The user entity.
        /// </value>
        public T_USER_Entity UserEntity
        {
            get { return ViewState["UserEntity"] as T_USER_Entity; }
            set { ViewState["UserEntity"] = value; }

        }

        private T_DEPARTMENT_BLL dBll = new T_DEPARTMENT_BLL();
        private T_USER_BLL uBll = new T_USER_BLL();
        private T_CONTENTAUTHORITY_BLL caBll = new T_CONTENTAUTHORITY_BLL();

        private T_MARKETDEPARTMENT_BLL marketDepartmentBll = new T_MARKETDEPARTMENT_BLL();
        private T_DEALER_BLL dealerBll = new T_DEALER_BLL();
        private T_SERVICEPROVIDER_BLL serviceProviderBll = new T_SERVICEPROVIDER_BLL();
        private T_SUPPLIER_BLL supplierBll = new T_SUPPLIER_BLL();

        protected override void OnInit(EventArgs e)
        {
            base.VerificationRight = false;
            base.OnInit(e);
            _userLoginInfo = UserLoginInfo.GetLoginInfo();
            PageHelper.SetPrePageUrl(this.Page);

        }

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                pageInit();


                tvDepartmentBinding();
            }
        }

        private void pageInit()
        {
            UserID = PageHelper.GetQueryString(this.Page, "UserID");
            UserEntity = uBll.GetEntity("UserID", UserID);
            if (UserEntity == null) return;
            lblUserName.Text = UserEntity.USERNAME;
            lblRoleName.Text = UserEntity.ROLENAME;
            lblDepartment.Text = UserEntity.DEPARTMENTNAME;



        }



        /// <summary>
        /// Tvs the department binding.
        /// </summary>
        private void tvDepartmentBinding()
        {
            tvDepartment.Nodes.Clear();
            List<T_USER_Entity> userList =
                uBll.GetList(String.Format(" and Status = '0' and BusinessDivisionCode = '{0}' ",
                                           UserEntity.BUSINESSDIVISIONCODE));
            List<T_CONTENTAUTHORITY_Entity> contentAuthorityList =
                caBll.GetList(String.Format(" and ViewPeopleID = {0} ", UserEntity.USERID));


            TreeNode node = new TreeNode();
            node.Text = "部门";
            node.ToolTip = "-1";
            switch ((UserType) Enum.Parse(typeof (UserType), UserEntity.USERTYPE.ToString()))
            {
                case UserType.中心部门:
                    {
                        List<T_DEPARTMENT_Entity> departmentList =
                            dBll.GetList(String.Format(" and Status = '0' and BusinessDivisionCode = '{0}' ",
                                                       UserEntity.BUSINESSDIVISIONCODE));
                        DepartmentRecursiveBinding(departmentList, userList, contentAuthorityList, "0", node);
                    }
                    break;
                case UserType.供应商:
                    {
                        List<T_SUPPLIER_Entity> supplierList =
                            supplierBll.GetList(String.Format(" and Status = '0' and BusinessDivisionCode = '{0}' ",
                                                              UserEntity.BUSINESSDIVISIONCODE));
                        DepartmentRecursiveBinding(supplierList, userList, contentAuthorityList,
                                                   UserEntity.DEPARTMENTID.ToString(), node);
                    }
                    break;
                case UserType.市场部:
                    {
                        List<T_MARKETDEPARTMENT_Entity> marketDepartmentList =
                            marketDepartmentBll.GetList(
                                String.Format(" and Status = '0' and BusinessDivisionCode = '{0}' ",
                                              UserEntity.BUSINESSDIVISIONCODE));
                        DepartmentRecursiveBinding(marketDepartmentList, userList, contentAuthorityList,
                                                   UserEntity.DEPARTMENTID.ToString(), node);

                    }
                    break;
                case UserType.服务商:
                    {
                        List<T_SERVICEPROVIDER_Entity> serviceProviderList =
                            serviceProviderBll.GetList(
                                String.Format(" and Status = '0' and BusinessDivisionCode = '{0}' ",
                                              UserEntity.BUSINESSDIVISIONCODE));
                        DepartmentRecursiveBinding(serviceProviderList, userList, contentAuthorityList,
                                                   UserEntity.DEPARTMENTID.ToString(), node);

                    }
                    break;
                case UserType.经销商:
                    {
                        List<T_DEALER_Entity> dealerList =
                            dealerBll.GetList(String.Format(" and Status = '0' and BusinessDivisionCode = '{0}' ",
                                                            UserEntity.BUSINESSDIVISIONCODE));
                        DepartmentRecursiveBinding(dealerList, userList, contentAuthorityList,
                                                   UserEntity.DEPARTMENTID.ToString(), node);

                    }
                    break;
                default:
                    {

                    }
                    break;
            }

            tvDepartment.Nodes.Add(node);
            tvDepartment.ExpandAll();
        }

        /// <summary>
        /// 经销商
        /// Departments the recursive binding.
        /// </summary>
        /// <param name="dealerList">The dealer list.</param>
        /// <param name="userList">The user list.</param>
        /// <param name="contentAuthorityList">The content authority list.</param>
        /// <param name="parentId">The parent id.</param>
        /// <param name="parentNode">The parent node.</param>
        private void DepartmentRecursiveBinding(List<T_DEALER_Entity> dealerList, List<T_USER_Entity> userList,
                                                List<T_CONTENTAUTHORITY_Entity> contentAuthorityList, string parentId,
                                                TreeNode parentNode)
        {
            List<T_DEALER_Entity> subdList = dealerList.FindAll(delegate(T_DEALER_Entity en)
                                                                    {
                                                                        if (en.DEALERID.ToString() == parentId)
                                                                            return true;
                                                                        return false;
                                                                    });
            foreach (T_DEALER_Entity entity in subdList)
            {
                TreeNode pNode = new TreeNode(entity.DEALERNAME.Trim(), entity.DEALERID.ToString());
                pNode.ToolTip = "-1";

                List<T_USER_Entity> subuList = userList.FindAll(delegate(T_USER_Entity u)
                                                                    {
                                                                        if (u.DEPARTMENTID.ToString() == parentId && (UserType)Enum.Parse(typeof (UserType), u.USERTYPE) ==UserType.经销商)
                                                                            return true;
                                                                        else
                                                                            return false;
                                                                    });
                foreach (T_USER_Entity userEntity in subuList)
                {
                    TreeNode node = new TreeNode(userEntity.USERNAME, userEntity.USERID.ToString());
                    node.Checked = contentAuthorityList.Exists(delegate(T_CONTENTAUTHORITY_Entity ca)
                                                                   {
                                                                       if (ca.VIEWEDPEOPLEID.ToString() == userEntity.USERID.ToString())
                                                                           return true;
                                                                       else
                                                                           return false;
                                                                   });
                    pNode.ChildNodes.Add(node);
                }

                parentNode.ChildNodes.Add(pNode);
            }
        }

        /// <summary>
        /// 服务商
        /// Departments the recursive binding.
        /// </summary>
        /// <param name="serviceProviderList">The service provider list.</param>
        /// <param name="userList">The user list.</param>
        /// <param name="contentAuthorityList">The content authority list.</param>
        /// <param name="parentId">The parent id.</param>
        /// <param name="parentNode">The parent node.</param>
        private void DepartmentRecursiveBinding(List<T_SERVICEPROVIDER_Entity> serviceProviderList,
                                                List<T_USER_Entity> userList,
                                                List<T_CONTENTAUTHORITY_Entity> contentAuthorityList, string parentId,
                                                TreeNode parentNode)
        {
            List<T_SERVICEPROVIDER_Entity> subdList = serviceProviderList.FindAll(delegate(T_SERVICEPROVIDER_Entity en)
                                                                                      {
                                                                                          if (
                                                                                              en.SERVICEPROVIDERID.
                                                                                                  ToString() == parentId)
                                                                                              return true;
                                                                                          return false;
                                                                                      });
            foreach (T_SERVICEPROVIDER_Entity entity in subdList)
            {
                TreeNode pNode = new TreeNode(entity.SERVICEPROVIDERNAME.Trim(), entity.SERVICEPROVIDERID.ToString());
                pNode.ToolTip = "-1";

                List<T_USER_Entity> subuList = userList.FindAll(delegate(T_USER_Entity u)
                                                                    {
                                                                        if (u.DEPARTMENTID.ToString() == parentId && (UserType)Enum.Parse(typeof(UserType), u.USERTYPE) == UserType.服务商)
                                                                            return true;
                                                                        else
                                                                            return false;
                                                                    });
                foreach (T_USER_Entity userEntity in subuList)
                {
                    TreeNode node = new TreeNode(userEntity.USERNAME, userEntity.USERID.ToString());
                    node.Checked = contentAuthorityList.Exists(delegate(T_CONTENTAUTHORITY_Entity ca)
                                                                   {
                                                                       if (ca.VIEWEDPEOPLEID.ToString() ==
                                                                           userEntity.USERID.ToString())
                                                                           return true;
                                                                       else
                                                                           return false;
                                                                   });
                    pNode.ChildNodes.Add(node);
                }

                parentNode.ChildNodes.Add(pNode);
            }
        }

        /// <summary>
        /// 市场部
        /// Departments the recursive binding.
        /// </summary>
        /// <param name="marketDepartmentList">The market department list.</param>
        /// <param name="userList">The user list.</param>
        /// <param name="contentAuthorityList">The content authority list.</param>
        /// <param name="parentId">The parent id.</param>
        /// <param name="parentNode">The parent node.</param>
        private void DepartmentRecursiveBinding(List<T_MARKETDEPARTMENT_Entity> marketDepartmentList,
                                                List<T_USER_Entity> userList,
                                                List<T_CONTENTAUTHORITY_Entity> contentAuthorityList, string parentId,
                                                TreeNode parentNode)
        {
            List<T_MARKETDEPARTMENT_Entity> subdList =
                marketDepartmentList.FindAll(delegate(T_MARKETDEPARTMENT_Entity en)
                                                 {
                                                     if (en.MARKETDEPARTMENTID.ToString() == parentId)
                                                         return true;
                                                     return false;
                                                 });
            foreach (T_MARKETDEPARTMENT_Entity entity in subdList)
            {
                TreeNode pNode = new TreeNode(entity.MARKETDEPARTMENTNAME.Trim(), entity.MARKETDEPARTMENTID.ToString());
                pNode.ToolTip = "-1";

                List<T_USER_Entity> subuList = userList.FindAll(delegate(T_USER_Entity u)
                                                                    {
                                                                        if (u.DEPARTMENTID.ToString() == parentId && (UserType)Enum.Parse(typeof(UserType), u.USERTYPE) == UserType.市场部)
                                                                            return true;
                                                                        else
                                                                            return false;
                                                                    });
                foreach (T_USER_Entity userEntity in subuList)
                {
                    TreeNode node = new TreeNode(userEntity.USERNAME, userEntity.USERID.ToString());
                    node.Checked = contentAuthorityList.Exists(delegate(T_CONTENTAUTHORITY_Entity ca)
                                                                   {
                                                                       if (ca.VIEWEDPEOPLEID.ToString() ==
                                                                           userEntity.USERID.ToString())
                                                                           return true;
                                                                       else
                                                                           return false;
                                                                   });
                    pNode.ChildNodes.Add(node);
                }

                parentNode.ChildNodes.Add(pNode);
            }
        }

        /// <summary>
        /// 供应商
        /// Departments the recursive binding.
        /// </summary>
        /// <param name="supplierList">The supplier list.</param>
        /// <param name="userList">The user list.</param>
        /// <param name="contentAuthorityList">The content authority list.</param>
        /// <param name="parentId">The parent id.</param>
        /// <param name="parentNode">The parent node.</param>
        private void DepartmentRecursiveBinding(List<T_SUPPLIER_Entity> supplierList, List<T_USER_Entity> userList,
                                                List<T_CONTENTAUTHORITY_Entity> contentAuthorityList, string parentId,
                                                TreeNode parentNode)
        {
            List<T_SUPPLIER_Entity> subdList = supplierList.FindAll(delegate(T_SUPPLIER_Entity en)
                                                                        {
                                                                            if (en.SUPPLIERID.ToString() == parentId)
                                                                                return true;
                                                                            return false;
                                                                        });
            foreach (T_SUPPLIER_Entity entity in subdList)
            {
                TreeNode pNode = new TreeNode(entity.SUPPLIERNAME.Trim(), entity.SUPPLIERID.ToString());
                pNode.ToolTip = "-1";

                List<T_USER_Entity> subuList = userList.FindAll(delegate(T_USER_Entity u)
                                                                    {
                                                                        if (u.DEPARTMENTID.ToString() == parentId && (UserType)Enum.Parse(typeof(UserType), u.USERTYPE) == UserType.供应商)
                                                                            return true;
                                                                        else
                                                                            return false;
                                                                    });
                foreach (T_USER_Entity userEntity in subuList)
                {
                    TreeNode node = new TreeNode(userEntity.USERNAME, userEntity.USERID.ToString());
                    node.Checked = contentAuthorityList.Exists(delegate(T_CONTENTAUTHORITY_Entity ca)
                                                                   {
                                                                       if (ca.VIEWEDPEOPLEID.ToString() ==
                                                                           userEntity.USERID.ToString())
                                                                           return true;
                                                                       else
                                                                           return false;
                                                                   });
                    pNode.ChildNodes.Add(node);
                }

                parentNode.ChildNodes.Add(pNode);
            }


        }

        /// <summary>
        /// 中心部门
        /// 递归 绑定下接列表。
        /// </summary>
        /// <param name="departmentList">The department list.</param>
        /// <param name="userList">The user list.</param>
        /// <param name="contentAuthorityList">The content authority list.</param>
        /// <param name="parentID">The parent ID.</param>
        /// <param name="parentNode">The parent node.</param>
        private void DepartmentRecursiveBinding(List<T_DEPARTMENT_Entity> departmentList, List<T_USER_Entity> userList,
                                                List<T_CONTENTAUTHORITY_Entity> contentAuthorityList, string parentID,
                                                TreeNode parentNode)
        {
            List<T_DEPARTMENT_Entity> subdList = departmentList.FindAll(delegate(T_DEPARTMENT_Entity m)
                                                                            {
                                                                                if (m.PDEPARTMENTID.ToString() ==
                                                                                    parentID)
                                                                                    return true;
                                                                                return false;
                                                                            });

            foreach (T_DEPARTMENT_Entity department in subdList)
            {
                TreeNode node = new TreeNode(department.DEPARTMENTNAME.Trim(), department.DEPARTMENTID.ToString());
                node.ToolTip = "-1";
                DepartmentRecursiveBinding(departmentList, userList, contentAuthorityList,
                                           department.DEPARTMENTID.ToString(), node);
                parentNode.ChildNodes.Add(node);
            }

            //
            List<T_USER_Entity> subuList = userList.FindAll(delegate(T_USER_Entity u)
                                                                {
                                                                    if (u.DEPARTMENTID.ToString() == parentID && (UserType)Enum.Parse(typeof(UserType), u.USERTYPE) == UserType.中心部门)
                                                                        return true;
                                                                    else
                                                                        return false;
                                                                });
            foreach (T_USER_Entity userEntity in subuList)
            {
                TreeNode node = new TreeNode(userEntity.USERNAME, userEntity.USERID.ToString());
                node.Checked = contentAuthorityList.Exists(delegate(T_CONTENTAUTHORITY_Entity ca)
                                                               {
                                                                   if (ca.VIEWEDPEOPLEID.ToString() ==
                                                                       userEntity.USERID.ToString())
                                                                       return true;
                                                                   else
                                                                       return false;
                                                               });
                parentNode.ChildNodes.Add(node);
            }



        }

        protected void btnOK_Click(object sender, EventArgs e)
        {
            List<T_CONTENTAUTHORITY_Entity> list = new List<T_CONTENTAUTHORITY_Entity>();
            getSelected(tvDepartment.Nodes, ref list);

            try
            {
                caBll.Delete("ViewPeopleID", UserID);
                foreach (T_CONTENTAUTHORITY_Entity en in list)
                {
                    caBll.Insert(en);
                }
                PageHelper.ExecuteJS("closeSelf();");
            }
            catch
            {
                PageHelper.ShowMessage("权限设置失败!");
            }
        }

        /// <summary>
        /// Gets the selected.
        /// </summary>
        /// <param name="nodes">The nodes.</param>
        /// <param name="list">The list.</param>
        private void getSelected(TreeNodeCollection nodes, ref List<T_CONTENTAUTHORITY_Entity> list)
        {
            foreach (TreeNode node in nodes)
            {
                if (node.Checked && (node.ToolTip.Trim() != "-1"))
                {
                    T_CONTENTAUTHORITY_Entity caEntity = new T_CONTENTAUTHORITY_Entity();
                    caEntity.VIEWPEOPLEID = UserEntity.USERID;
                    caEntity.BUSINESSDIVISIONCODE = UserEntity.BUSINESSDIVISIONCODE;
                    caEntity.BUSINESSDIVISIONID = UserEntity.BUSINESSDIVISIONID;
                    caEntity.BUSINESSDIVISIONNAME = UserEntity.BUSINESSDIVISIONNAME;
                    caEntity.CREATEPEOPLE = _userLoginInfo.UserEntity.USERNAME;
                    caEntity.CREATEPEOPLEID = _userLoginInfo.UserEntity.USERID;
                    caEntity.CREATETIME = DateTime.Now;
                    caEntity.LASTMODIFYPEOPLE = _userLoginInfo.UserEntity.USERNAME;
                    caEntity.LASTMODIFYPEOPLEID = _userLoginInfo.UserEntity.USERID;
                    caEntity.LASTMODIFYTIME = DateTime.Now;
                    caEntity.STATUS = 0;
                    caEntity.VIEWDEPARTMENTID = UserEntity.DEPARTMENTID;
                    caEntity.VIEWDEPARTMENTNAME = UserEntity.DEPARTMENTNAME;
                    caEntity.VIEWEDDEPARTMENTID = (node.Parent == null) ? 0 : StringHelper.ToInt(node.Parent.Value, 0);
                    caEntity.VIEWEDDEPARTMENTNAME = (node.Parent == null) ? "" : node.Parent.Text;
                    caEntity.VIEWEDPEOPLEID = StringHelper.ToInt(node.Value.Trim());
                    list.Add(caEntity);
                }
                getSelected(node.ChildNodes, ref list);
            }
        }



    }
}
